package com.toumy.controller;

import com.toumy.domain.Book;
import com.toumy.domain.Code;
import com.toumy.domain.Result;
import com.toumy.service.IBookService;
import com.toumy.service.ImgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;


@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private IBookService iBookService;
    @Autowired
    private ImgService imgService;

    @GetMapping("/{id}")
    public Result getById(@PathVariable int id){
        Book book = iBookService.getById(id);
        return book != null?new Result(Code.FIND_S,book,"查找成功"):new Result(Code.FIND_F,null,"查找失败");
    }

    @GetMapping("/cate/{cate}")
    public Result getByCate(@PathVariable int cate){
        List<Book> books = iBookService.SelectByCate(cate);

        return books.size() != 0?new Result(Code.FIND_S,books,"查找成功"):new Result(Code.FIND_F,null,"无对应项");
    }

    @GetMapping("/owner/{owner}")
    public Result getByOwner(@PathVariable int owner){
        List<Book> books = iBookService.SelectByOwner(owner);

        return books.size() != 0?new Result(Code.FIND_S,books,"查找成功"):new Result(Code.FIND_F,null,"无对应项");
    }

    @GetMapping
    public Result getAll(){
        List<Book> books = iBookService.list();

        return books != null?new Result(Code.FIND_S,books,"查找成功"):new Result(Code.FIND_F,null,"查找失败");
    }

    @PostMapping
    public Result addBook(@RequestBody Book book){
        boolean flag = iBookService.save(book);

        return flag?new Result(Code.ADD_S,book,"添加成功"):new Result(Code.ADD_F,null,"添加失败");
    }

    @DeleteMapping("/{id}")
    public Result deleteBook(@PathVariable int id){
        Book book = iBookService.getById(id);
        String[] keys = {book.getImg1(),book.getImg2(),book.getImg3()};

        boolean flag1 = imgService.delete(keys);
        boolean flag2 = iBookService.removeById(id);

        return flag1&&flag2?new Result(Code.DELETE_S,null,"删除成功"):new Result(Code.DELETE_F,null,"删除失败");
    }
}
